<template>
  <div class="video-category-container">
    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="handleClick(null, 0, '新增类型')"
          >新增</el-button
        >
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="30%"
        >
          <el-form
            label-position="left"
            label-width="100px"
            :model="categoryForm"
            :rules="rules"
            ref="categoryForm"
          >
            <el-form-item prop="parentId" label="上级类别">
              <el-select
                clearable
                :disabled="formType === 1"
                v-model="categoryForm.parentId"
                placeholder="根类别"
              >
                <el-option
                  v-for="item in rootCategorys"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input
                :disabled="formType === 1"
                v-model="categoryForm.name"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
            <el-form-item label="菜单图标" v-if="categoryForm.parentId === null || categoryForm.parentId===''">
              <el-upload
                class="avatar-uploader"
                :action="imgUploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="categoryForm.icon"
                  :src="categoryForm.icon"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- <el-form-item label="菜单图标">
              <el-popover
                :disabled="formType === 1"
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input
                  :disabled="formType === 1"
                  slot="reference"
                  v-model="categoryForm.icon"
                  placeholder="点击选择图标"
                  readonly
                >
                  <svg-icon
                    v-if="categoryForm.icon"
                    slot="prefix"
                    :icon-class="categoryForm.icon"
                    class="el-input__icon"
                    style="height: 32px; width: 16px"
                  />
                  <i
                    v-else
                    slot="prefix"
                    class="el-icon-search el-input__icon"
                  />
                </el-input>
              </el-popover>
            </el-form-item> -->
            <el-form-item prop="status" label="启用">
              <el-switch
                :disabled="formType === 1"
                v-model="categoryForm.status"
                active-value="0"
                inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </el-form-item>
            <el-form-item prop="sort" label="排序">
              <el-input-number
                :disabled="formType === 1"
                v-model="categoryForm.sort"
                :min="1"
                label="描述文字"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              v-if="
                categoryForm.parentId != null && categoryForm.parentId != ''
              "
              label="标签"
              prop="checkLabelIds"
            >
              <el-tree
                :check-strictly="true"
                :data="labelDatas"
                show-checkbox
                node-key="id"
                :default-checked-keys="categoryForm.checkLabelIds"
                ref="labelTree"
                :props="{ children: 'children', label: 'name' }"
              ></el-tree>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button
              v-if="formType !== 1"
              :loading="loading"
              type="primary"
              @click="confirmHandel('categoryForm')"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          :data="pagination.categoryDatas"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="index" width="30px"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="sort" label="排序"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '0' ? 'success' : 'danger'"
                disable-transitions
                >{{ scope.row.status === "0" ? "启用" : "禁用" }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150px">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row, 1, '类型详情')"
                type="text"
                size="small"
                >查看</el-button
              >
              <el-button
                @click="handleClick(scope.row, 2, '编辑类型')"
                type="text"
                size="small"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.sign !== 'SUPER_ADMIN'"
                @click="delCategory(scope.row)"
                type="text"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="pagination.pageSizeChoose"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getPaginationList,
  getCategoryList,
  add,
  delCategory,
  getDetails,
  updateCategory,
} from "@/api/video/category";
import { getLabelList } from "@/api/video/label";
// import IconSelect from "@/components/IconSelect";
import { cascaderDisabledSelf } from "@/utils/common";

export default {
  name: "VideoCategory",
  created() {
    this.getPaginationCategorys();
  },
  data() {
    return {
      imgUploadUrl:
        process.env.VUE_APP_BASE_API + '/file/upload',
      labelDatas: [],
      formType: 0,
      loading: false,
      rootCategorys: [],
      dialogVisible: false,
      dialogTitle: "",
      categoryForm: {
        name: null,
        sort: null,
        icon: null,
        parentId: null,
        checkLabelIds: [],
        delLabelIds: [],
        addLabelIds: [],
        status: "0",
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizeChoose: [5, 10, 15, 20],
        total: 0,
        categoryDatas: [],
      },
      rules: {
        sign: [{ required: true, message: "请输入标识", trigger: "blur" }],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },

  watch: {
    dialogVisible: function () {
      if (this.dialogVisible === false) {
        this.$refs["categoryForm"].resetFields();
        this.categoryForm.icon = null;
        this.labelDatas = [];
      } else {
        getCategoryList({ parentId: 0 }).then((response) => {
          this.rootCategorys = response.data;
          cascaderDisabledSelf(this.rootCategorys, this.categoryForm);
        });
        getLabelList().then((response) => {
          this.labelDatas = response.data;
        });
      }
    },
  },
  methods: {
    // 选择图标
    selected(name) {
      this.categoryForm.icon = name;
    },
    delCategory(role) {
      this.$confirm(
        '是否确认删除类型名为"' + role.name + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delCategory(role.id);
        })
        .then(() => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getPaginationCategorys();
        })
        .catch(function () {});
    },
    addCategory() {
      this.loading = true;
      add(this.categoryForm)
        .then(() => {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationCategorys();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updateCategory() {
      this.loading = true;
      updateCategory(this.categoryForm)
        .then(() => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationCategorys();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    checkNewLabels() {
      const newcheckLabelIds = this.$refs.labelTree.getCheckedKeys();
      this.categoryForm.checkLabelIds.forEach((item) => {
        if (newcheckLabelIds.indexOf(item) < 0) {
          this.categoryForm.delLabelIds.push(item);
        }
      });
      newcheckLabelIds.forEach((item) => {
        if (this.categoryForm.checkLabelIds.indexOf(item) < 0) {
          this.categoryForm.addLabelIds.push(item);
        }
      });
    },
    confirmHandel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formType === 0) {
            if (this.categoryForm.parentId !== null) {
              this.categoryForm.addLabelIds = this.$refs.labelTree.getCheckedKeys();
            }
            this.addCategory();
          } else if (this.formType === 2) {
            this.checkNewLabels();
            this.updateCategory();
          }
          this.loading = true;
        }
      });
    },
    getPaginationCategorys() {
      const params = {
        pageSize: this.pagination.pageSize,
        pageIndex: this.pagination.currentPage,
      };
      getPaginationList(params).then((res) => {
        this.pagination.categoryDatas = res.data.records;
        this.pagination.total = res.data.total;
      });
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getPaginationCategorys();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getPaginationCategorys();
    },
    handleClick(data, type, title) {
      if (type !== 0) {
        getDetails(data.id).then((response) => {
          this.categoryForm = response.data;
          this.categoryForm.checkLabelIds = response.data.labelIds;
          this.categoryForm.delLabelIds = [];
          this.categoryForm.addLabelIds = [];
          if(this.categoryForm.parentId === 0){
            this.categoryForm.parentId = null
          }
        });
      }
      this.dialogTitle = title;
      this.formType = type;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res) {
      if (res.code != 200) {
        this.$message.error(res.msg);
      } else {
        this.categoryForm.icon = res.data
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.video-category-container {
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>